import { RouteRecordRaw } from 'vue-router';
import { asyncRoutes } from './index';
import { getMenuList as getMenuListApi } from '@/api/menu';

// 菜单项接口定义
interface MenuItem {
  id: string;
  name: string;
  path: string;
  icon?: string;
  funcodeId?: string;
  isHidden?: boolean;
  children?: MenuItem[];
}

/**
 * 递归检查菜单列表中是否包含指定的funcodeId
 * @param menuList 菜单列表
 * @param funcodeId 要检查的funcodeId
 */
function hasFuncodeId(menuList: MenuItem[], funcodeId: string): boolean {
  for (const item of menuList) {
    if (item.funcodeId === funcodeId) {
      return true;
    }
    if (item.children && hasFuncodeId(item.children, funcodeId)) {
      return true;
    }
  }
  return false;
}

/**
 * 判断用户是否有权限访问该路由
 * @param route 路由
 * @param menuList 菜单列表
 */
function hasPermission(route: RouteRecordRaw, menuList: MenuItem[]): boolean {
  // 如果没有funcodeId，默认允许访问
  if (!route.meta || !route.meta.funcodeId) {
    return true;
  }

  // 检查菜单列表中是否包含该funcodeId
  return hasFuncodeId(menuList, route.meta.funcodeId as string);
}

/**
 * 过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes 异步路由表
 * @param menuList 菜单列表
 */
export function filterAsyncRoutes(
  routes: RouteRecordRaw[],
  menuList: MenuItem[]
): RouteRecordRaw[] {
  const res: RouteRecordRaw[] = [];

  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(tmp, menuList)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menuList);
      }
      res.push(tmp);
    }
  });

  return res;
}

/**
 * 生成动态路由
 */
export async function generateDynamicRoutes(): Promise<RouteRecordRaw[]> {
  try {
    // 获取菜单列表
    let menuList: MenuItem[] = [];
    const res = await getMenuListApi();
    if (res.code === 200) {
      menuList = res.data;
    }

    // 过滤路由
    const filteredRoutes = filterAsyncRoutes(asyncRoutes, menuList);

    return filteredRoutes;
  } catch (error) {
    return [];
  }
}
